<?php

declare(strict_types=1);

namespace App\Model;

use App\Helpers\AliyunUtil;
use Hyperf\DbConnection\Db;
use Hyperf\DbConnection\Model\Model;

/**
 * 背包礼物
 */
class UserPackBag extends Model
{
    protected $table = 'user_pack_bags';

    const STATUS_NOT_USED = 0;
    const STATUS_USED = 1;

    static function addRecord($userId = 0, $giftId = 1, $giftNum = 1)
    {
        for ($i = 1; $i <= $giftNum; $i++) {
            $model = new self();
            $model->user_id = $userId;
            $model->gift_id = $giftId;
            $model->flag = self::STATUS_NOT_USED;
            $model->saveOrFail();
        }
    }

    static function getList($userId = 0)
    {
        $where = [
            'user_id' => $userId,
            'flag' => self::STATUS_NOT_USED,
        ];
        $data = self::where($where)->select(['gift_id', Db::raw('count(1) as ctn')])->groupBy('gift_id')->get()->toArray();
        return $data;
    }

    /**
     * 背包礼物
     */
    static function usePackBag($userId = 0, $giftId = 1, $giftNum = 1)
    {
        $where = [
            'user_id' => $userId,
            'gift_id' => $giftId,
            'flag' => self::STATUS_NOT_USED,
        ];
        if (self::where($where)->count() < $giftNum) return false;
        return self::where($where)->limit($giftNum)->update([
            'flag' => self::STATUS_USED,
            'used_at' => date('Y-m-d H:i:s')
        ]);
    }
}
